package com.vhall.component.framework.common.utils;

import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternBuilder {

    private Pattern pattern;

    /**
     * 生成正则表达式
     *
     * @return
     */
    private static String toUrlPattern(List<String> urls) {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        if (CollectionUtils.isNotEmpty(urls)) {
            for (String url : urls) {
                sb.append(url).append("|");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append(")");
        return sb.toString();
    }

    /**
     * 空参构建
     *
     * @return
     */
    public static PatternBuilder build() {
        return build(null);
    }

    /**
     * 构建正则表达式
     *
     * @param urls
     * @return
     */
    public static PatternBuilder build(List<String> urls) {
        PatternBuilder builder = new PatternBuilder();
        if (CollectionUtils.isNotEmpty(urls)) {
            builder.setPattern(Pattern.compile(toUrlPattern(urls)));
        }
        return builder;
    }

    private void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    /**
     * 重新构建正则表达式
     *
     * @param urls
     */
    public void rebuild(List<String> urls) {
        if (CollectionUtils.isNotEmpty(urls)) {
            this.pattern = Pattern.compile(toUrlPattern(urls));
        }
    }

    /**
     * 转成正则表达式
     *
     * @param value
     * @return
     */
    public static String toPatternValue(String value) {
        if (value.contains("*")) {
            return value.replaceAll("\\*+", ".*");
        }
        return value;
    }

    /**
     * 获取正则表达式结果
     *
     * @return
     */
    public String matcher(String charsequence, int group) {
        if (Objects.isNull(pattern) || Objects.isNull(charsequence)) {
            return null;
        }
        Matcher matcher = pattern.matcher(charsequence);
        if (matcher.find()) {
            return matcher.group(group);
        }
        return null;
    }

    /**
     * 匹配字符串
     *
     * @param charsequence
     * @return
     */
    public boolean matcher(String charsequence) {
        return Objects.nonNull(pattern) && pattern.matcher(charsequence).find();
    }

    @Override
    public int hashCode() {
        return (pattern == null) ? 0 : pattern.toString().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (Objects.isNull(obj)) {
            return false;
        }
        PatternBuilder other = (PatternBuilder) obj;
        return pattern.toString().equals(other.pattern.toString());
    }

    @Override
    public String toString() {
        return (pattern != null) ? pattern.toString() : null;
    }
}
